package app.dws;

import Bean.CartAddUuBean;
import app.dwd.BaseAppV1;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import util.AtguiguUtil;
import util.FlinkSinkUtil;

import java.time.Duration;

/**
 * @author cheng
 * @create 2022-10-26 20:27
 */
public class Dws_CartAdd extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_CartAdd().init(4011,2,"Dws_CartAdd", Constant.TOPIC_DWD_TRADE_CART_ADD);
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
stream
        .map(JSON::parseObject)
        .assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((obj, ts) -> obj.getLong("ts") * 1000)
        )
        .keyBy(obj -> obj.getString("user_id"))
        .process(new KeyedProcessFunction<String, JSONObject, CartAddUuBean>() {
            private ValueState<String> lastCartAddDateState;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastCartAddDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastCartAddDateState", String.class));
            }

            @Override
            public void processElement(JSONObject jsonObject, Context context, Collector<CartAddUuBean> collector) throws Exception {
                String lastCartAddDate = lastCartAddDateState.value();
                long ts = jsonObject.getLong("ts") * 1000;
                String today = AtguiguUtil.toDate(ts);

                if (!today.equals(lastCartAddDate)) {
                    lastCartAddDateState.update(today);

                    collector.collect(new CartAddUuBean("", "", 1L, ts));
                }
            }
        })
        .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
        .reduce(
                new ReduceFunction<CartAddUuBean>() {
                    @Override
                    public CartAddUuBean reduce(CartAddUuBean value1,
                                                CartAddUuBean value2) throws Exception {
                        value1.setCartAddUuCt(value1.getCartAddUuCt() + value2.getCartAddUuCt());
                        return value1;
                    }
                },
                new AllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window,
                                      Iterable<CartAddUuBean> values,
                                      Collector<CartAddUuBean> out) throws Exception {
                        CartAddUuBean bean = values.iterator().next();
                        bean.setStt(AtguiguUtil.toDatTime(window.getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(window.getEnd()));

                        bean.setTs(System.currentTimeMillis());

                        out.collect(bean);
                    }
                }
        )
//        .print();
        .addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_cart_add_uu_window", CartAddUuBean.class));


    }
}
